package com.yidu.ruifeng_logistics.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.github.pagehelper.util.StringUtil;
import com.yidu.ruifeng_logistics.entity.*;
import com.yidu.ruifeng_logistics.service.*;
import com.yidu.ruifeng_logistics.utils.BaseMessage;
import com.yidu.ruifeng_logistics.vo.LogisticsModelVo;
import com.yidu.ruifeng_logistics.vo.LogisticsRoleModelVo;
import com.yidu.ruifeng_logistics.vo.LogisticsStaffVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * (LogisticsStaff)表控制层
 *
 * @author 张皓超
 * @since 2021-03-09 14:29:20
 */
@Api(description = "员工接口")
@RestController
@RequestMapping("logisticsStaff")
public class LogisticsStaffController {

    @Resource
    RedisTemplate redisTemplate ;//redis

    /**
     * 服务对象
     */
    @Resource
    private LogisticsStaffService logisticsStaffService;

    /**
     * 员工角色模块表
     */
    @Resource
    private LogisticsUserRoleService logisticsUserRoleService;

    /**
     * 角色表
     */
    @Resource
    private LogisticsRoleService logisticsRoleService;
    /**
     * 注入角色模块表
     */
    @Resource
    private LogisticsRoleModelService logisticsRoleModelService;

    /**
     * 注入模块表
     */
    @Resource
    private LogisticsModelService logisticsModelService;

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public LogisticsStaff selectOne(Integer id) {
        return this.logisticsStaffService.queryById(id);
    }

    /**
     * 根据id删除
     * @param staffId
     * @return
     */
    @PostMapping("deleteId")
    public BaseMessage deleteId(Integer staffId) {
        boolean b = this.logisticsStaffService.deleteById(staffId);
        return b == false ? BaseMessage.fail() : BaseMessage.success();
    }

    /**
     * 遍历all
     *
     * @param staff
     * @return
     */
    @ApiOperation(value = "遍历员工", notes = "返回BaseMessage")
    @GetMapping("findAll")
    public Map findAll(Integer page, Integer limit, LogisticsStaff staff) {
        PageHelper.startPage(page, limit);
        List<LogisticsStaff> list = logisticsStaffService.queryAll(staff);
        Map<String, Object> map = new HashMap<>();
        PageInfo<LogisticsStaff> pageInfo = new PageInfo<>(list);
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("data", pageInfo.getList());//可以直接写list
        map.put("count", pageInfo.getTotal()); //总行数
        return map;
    }

    /**
     * 数据回显
     *
     * @param
     * @return
     */
    @ApiOperation(value = "数据回显", notes = "返回BaseMessage")
    @PostMapping("show")
    public BaseMessage show(Integer staffId) {
        Map<String, Object> map = new HashMap<>();
        LogisticsStaff logisticsStaff = logisticsStaffService.queryById(staffId);
        map.put("data1", logisticsStaff);
        List<LogisticsUserRole> logisticsUserRoles = logisticsUserRoleService.queryStaffIdReturnObj(staffId);
        map.put("data2", logisticsUserRoles);
        return BaseMessage.success(map);
    }

    @ApiOperation(value = "得到树形组件数据", notes = "返回BaseMessage")
    @PostMapping("yaoDate")
    public BaseMessage yaoDate() {
        List<LogisticsRole> logisticsRoles = logisticsRoleService.queryAll(new LogisticsRole());
        return BaseMessage.success(logisticsRoles);
    }

    /**
     * 增加修该
     *
     * @param vo
     * @return
     */
    @ApiOperation(value = "增加修改", notes = "返回BaseMessage")
    @PostMapping("addAndUpdate")
    public BaseMessage addAndUpdate(LogisticsStaffVo vo,
                                    @RequestParam(value = "staffPhoto_", required = false) MultipartFile file,
                                    HttpServletRequest request,
                                    String suserRoleId) {

        String fileName = file.getOriginalFilename();
        if (!StringUtils.isEmpty(fileName)) {
            int index = fileName.lastIndexOf('.');
            String hz = fileName.substring(index);

            //使用jdk提供的随机字符串
            String newFileName = UUID.randomUUID().toString() + hz;
            //真实路径
            String realPath = request.getServletContext().getRealPath("file:");
            File target = new File("D://otherfiles//upload//"+newFileName);
            try {
                //保存文件
                file.transferTo(target);
            } catch (IOException e) {
                e.printStackTrace();
            }
            vo.setStaffPhoto("/img/" + newFileName);
        }
        return logisticsStaffService.addAndUpdate(vo, suserRoleId) > 0 ? BaseMessage.success() : BaseMessage.fail();
    }



    /**
     * @param session
     * @return
     */
    @ApiOperation(value = "需要session", notes = "返回BaseMessage")
    @PostMapping("queryAll")
    public Map<String, Object>  queryAll(HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        Map<String, Object> queryFll = null;
        if(!StringUtils.isEmpty(userName)){
            queryFll = (Map<String, Object>)redisTemplate.opsForValue().get(userName+"_queryFll");
        }

        if (queryFll==null) {
            Object o = session.getAttribute("identity");

            Map<String, Object> map = new HashMap();
            if (o != null && o != "") {
                if ("client".equals(o)) {
                    //客户
                    List<LogisticsModel> logisticsModels = logisticsModelService.queryClient("客户");//取得客户模块的根目录
                    List<LogisticsModelVo> list = new ArrayList<>();
                    for (LogisticsModel model : logisticsModels) {
                        LogisticsModelVo logisticsModelVo = new LogisticsModelVo();
                        logisticsModelVo.setModelId(model.getModelId());
                        logisticsModelVo.setModelName(model.getModelName());
                        logisticsModelVo.setModelRemark(model.getModelRemark());
                        logisticsModelVo.setModelUrl(model.getModelUrl());
                        logisticsModelVo.setModelParent(model.getModelParent());
                        logisticsModelVo.setLogisticsModelVos(selectF(model.getModelId()));//调用递归
                        list.add(logisticsModelVo);//放进树形组件
                    }
                    //取seeion 得到客户对象
                    LogisticsClient login = (LogisticsClient) session.getAttribute("login");
                    map.put("state", 1);
                    map.put("msg", "操作成功");
                    map.put("data", list);
                    map.put("name", login.getClientName());
                    map.put("id", login.getClientId());
                    redisTemplate.opsForValue().set(userName+"_queryFll", map);
                    return map;//数据
                } else if ("staff".equals(o)) {
                    //员工
                    LogisticsStaff staff = (LogisticsStaff) session.getAttribute("login");//取出员工seeion对象
                    //得到用户角色
                    List<LogisticsUserRole> logisticsUserRoles = logisticsUserRoleService.queryStaffIdReturnObj(staff.getStaffId());
                    //假如该员工有多个角色
                    for (LogisticsUserRole logisticsUserRole : logisticsUserRoles) {
                        //根据角色id返回模块id
                        List<Integer> modelIds = logisticsRoleModelService.selectRoleIdReturnModelId(logisticsUserRole.getRoleId());
                        List<LogisticsModelVo> logisticsModelVoLists = new ArrayList<>();//页面需要的list
                        for (Integer modelId1 : modelIds) {
                            if (logisticsModelService.selectModelParentIsNull(modelId1) > 0) {//如果是空 就是根目录
                                LogisticsModelVo logisticsModelVo = new LogisticsModelVo();
                                LogisticsModel logisticsModel = logisticsModelService.queryById(modelId1);
                                BeanUtils.copyProperties(logisticsModel, logisticsModelVo);
                                logisticsModelVo.setLogisticsModelVos(selectF(modelId1, modelIds));
                                logisticsModelVoLists.add(logisticsModelVo);
                            }
                        }
                        map.put("state", 1);
                        map.put("msg", "操作成功");
                        map.put("data", logisticsModelVoLists);
                        map.put("name", staff.getStaffName());
                        map.put("id", staff.getStaffId());
                        redisTemplate.opsForValue().set(userName+"_queryFll", map);
                        return map;
                    }
                } else {
                    map.put("state", 0);
                    map.put("msg", "操作失败");
                    return map;
                }
            } else {
                map.put("state", 0);
                map.put("msg", "操作失败");
                return map;
            }
        }
        return queryFll;
    }


    /**
     * 树形递归
     *
     * @param roleId
     * @return
     */
    public List<LogisticsModelVo> selectF(Integer roleId) {

        List<LogisticsModelVo> list = new ArrayList<>();
        List<LogisticsModel> modelList = logisticsModelService.selectI(roleId);

        for (int i = 0; i < modelList.size(); i++) {
            LogisticsModelVo logisticsModelVo = new LogisticsModelVo();
            logisticsModelVo.setModelId(modelList.get(i).getModelId());
            logisticsModelVo.setModelName(modelList.get(i).getModelName());
            logisticsModelVo.setModelRemark(modelList.get(i).getModelRemark());
            logisticsModelVo.setModelUrl(modelList.get(i).getModelUrl());
            logisticsModelVo.setModelParent(modelList.get(i).getModelParent());
            if (roleId != modelList.get(i).getModelParent()) {
                return list;
            } else {
                logisticsModelVo.setLogisticsModelVos(selectF(modelList.get(i).getModelId()));//递归
                list.add(logisticsModelVo);
            }
        }

        return list;
    }

    /**
     * 树形递归
     *
     * @param roleId
     * @return
     */
    public List<LogisticsModelVo> selectF(Integer roleId,List<Integer> modelIds) {

        List<LogisticsModelVo> list = new ArrayList<>();
        List<LogisticsModel> modelList = logisticsModelService.selectI(roleId);
        for (Integer modelId : modelIds) {
            for (int i = 0; i < modelList.size(); i++) {
                if (modelList.get(i).getModelId() == modelId) {
                    LogisticsModelVo logisticsModelVo = new LogisticsModelVo();
                    logisticsModelVo.setModelId(modelList.get(i).getModelId());
                    logisticsModelVo.setModelName(modelList.get(i).getModelName());
                    logisticsModelVo.setModelRemark(modelList.get(i).getModelRemark());
                    logisticsModelVo.setModelUrl(modelList.get(i).getModelUrl());
                    logisticsModelVo.setModelParent(modelList.get(i).getModelParent());
                    if (roleId != modelList.get(i).getModelParent()) {
                        return list;
                    } else {
                        logisticsModelVo.setLogisticsModelVos(selectF(modelList.get(i).getModelId(),modelIds));//递归
                        list.add(logisticsModelVo);
                    }
                }
            }
        }
        return list;
    }

}
